/*
 * @lc app=leetcode.cn id=59 lang=cpp
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
class Solution
{
public:
  vector<vector<int>> generateMatrix(int n)
  {
    vector<vector<int>> ans(n, vector<int>(n));
    int L = 0, R = n - 1, U = 0, D = n - 1;
    int seq = 1;
    while (L <= R) {
      // L -> R
      for (int i = L; i <= R; ++i)
        ans[U][i] = seq++;
      ++U;
      // U -> D
      for (int i = U; i <= D; ++i)
        ans[i][R] = seq++;
      --R;
      // R -> L
      for (int i = R; i >= L; --i)
        ans[D][i] = seq++;
      --D;
      // D -> U
      for (int i = D; i >= U; --i)
        ans[i][L] = seq++;
      ++L;
    }
    return ans;
  }
};
// @lc code=end
